package utils

import (
	"fmt"
	"gitee.com/ymofen/gobase/gotask/grouptask"
	"os"
	"sync/atomic"
	"time"
)

var (
	defaultTWCreateFlag int32 = 0
	defaultTW           *TimeWheel
)

func checkDefaultTimeWheel() (newflag byte) {
	if defaultTW == nil {
		if atomic.CompareAndSwapInt32(&defaultTWCreateFlag, 0, 1) {
			defaultTW = NewTW(time.Millisecond * 100)
			defaultTW.ConfigExecTaskFunc(Func_ExecTask_GroupSync)
			go defaultTW.Start()

			return 1
		} else {
			time.Sleep(time.Millisecond * 100)
		}
	}
	if defaultTW == nil {
		panic("defaultTW")
	}
	return 0
}

func GetDefaultTW() *TimeWheel {
	checkDefaultTimeWheel()
	return defaultTW
}

func Func_ExecTask_GroupSync(rec *TWTaskRec) {
	err := grouptask.DefaultGroupTask().PostTaskFunc(rec.id, func() {
		rec.DoTask()
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, fmt.Sprintf("[%s]投递异步任务到组[%v]出现异常:%s, 任务未被执行!\n", NowString(), rec.id, err.Error()))
	}
}

func ConfigDefaultTWExecTask_GroupSync() {
	GetDefaultTW().ConfigExecTaskFunc(Func_ExecTask_GroupSync)
}

func AddTaskIntervalEx(id interface{}, interval time.Duration, fn func() bool) {
	checkDefaultTimeWheel()
	defaultTW.AddTaskInterval(id, fn, interval, ZeroTime)
	return
}

func AddTaskInterval(id interface{}, fn func() bool, interval time.Duration, startTime time.Time) bool {
	checkDefaultTimeWheel()
	defaultTW.AddTaskInterval(id, fn, interval, startTime)
	return true
}

func AddTaskAfterInterval(id interface{}, after, interval time.Duration, fn func() bool) bool {
	checkDefaultTimeWheel()
	defaultTW.AddTaskAfterInterval(id, after, interval, fn)
	return true
}

func AddTaskFxiedInterval(id interface{}, interval time.Duration, fn func() bool) bool {
	checkDefaultTimeWheel()
	defaultTW.AddTaskFixedInterval(id, interval, fn)
	return true
}

func AfterExecute(id interface{}, afterTime time.Duration, fn func()) {
	checkDefaultTimeWheel()
	defaultTW.AddTaskNextTime(id, fn, time.Now().Add(afterTime))
}
